package com.project.core.interceptor;

import com.project.core.constant.ScoreConstant;
import com.project.core.util.CommonUtil;
import com.project.core.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Objects;

/**
 * @author mengxj
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object obj = request.getHeader(ScoreConstant.ACCESS_TOKEN);
        if(Objects.isNull(obj)){
            CommonUtil.throwException(ScoreConstant.AUTH_ERROR_CODE, "请求需携带token");
        }
        String token = obj.toString();
        Claims claims = this.jwtUtil.getClaimByToken(token);
        Date now = new Date();
        if(Objects.nonNull(claims) && claims.getExpiration().after(now)){
            return true;
        }
        request.getRequestDispatcher("/user/refresh-token").forward(request, response);
        return false;
    }
}
